In this tutorial, we will learn how to use the array find method in Vue.js to find an array of objects by its ID or item in the array. This method iterates over the array and returns the first element that satisfies the criteria established by a test function, whether you’re searching for an object by its ID or a particular item in the array.
Example 1 : Vue Js Search Array of Objects
In the code below, we implement a search for a value within an array of objects by its ID using the array.find()
method. If you want to customize this provided code, click on the ‘Try it’ button to modify the code according to your project requirements.
Vue Js array find Method Example
<script type="module">
import {createApp} from 'vue'
createApp({
data() {
return {
employees: [{
'id': '1',
'name': 'David',
'role': 'Web Developer'
}, {
'id': '2',
'name': 'Andrew',
'role': 'Frontend Developer'
}, {
'id': '3',
'name': 'Smith',
'role': 'Backend Developer'
}],
searchId: '2',
result: null
}
},
methods: {
myFunction() {
const idToFind = this.searchId.trim();
this.result = this.employees.find((employee) => employee.id === idToFind);
}
}
}).mount('#app')
</script>
Output of Find Object in array by Property Value
Example 2 : Vue js Array Find Method
You can use the array.find
method in Vue to search for a query within an array. Check out the code below and use it in your required project
The JavaScript find method can be used to find the array element by passes test in Vue.js.
Vue Js Find Value in Array
<script type="module">
const app = Vue.createApp({
data() {
return {
fruits: ['apple', 'grapes', 'banana', 'orange'],
searchFruitInput: '',
foundFruit: ''
};
},
methods: {
searchFruit() {
this.foundFruit = this.fruits.find(fruit => fruit === this.searchFruitInput);
}
}
});
app.mount("#app");
</script>